/**
 * @author chensj
 * @title
 * @email chensj@winning.com.cn
 * @package
 * @date: 2019-04-29 16:55
 */

/**
 * @Author jinxl
 * @Explain  API
 */

import url from './url/index'
import { Notification } from 'element-ui'
import Storage from '../utils/storage'
const config = require('../../config')
const axios = require('axios')
const serverUrl = 'http://localhost:8081/'
// const serverUrl = 'http://mbk.winning.com.cn:8090/'
const shareUrl = 'http://mbk.winning.com.cn:8091/ftp'
const mockUrl = process.env.NODE_ENV === 'production'
  ? config.build.assetsPublicPath + config.build.assetsSubDirectory
  : config.dev.assetsPublicPath + config.dev.assetsSubDirectory
// 封装头部信息
axios.defaults.headers = {
  'X-Requested-With': 'XMLHttpRequest',
  'Content-Type': 'application/x-www-form-urlencoded'
}
// 失效时间
axios.defaults.timeout = 600000
// 跨域请求携带session
axios.defaults.withCredentials = true
let cancel
const promiseArr = {}
// const CancelToken = axios.CancelToken
// 请求拦截器
axios.interceptors.request.use(config => {
  if (Storage.getLocalStorage('username')) {
    config.headers.token = Storage.getLocalStorage('username')
  }
  // 发起请求时，取消掉当前正在进行的相同请求
  if (promiseArr[config.url]) {
    promiseArr[config.url]('操作取消')
    promiseArr[config.url] = cancel
  } else {
    promiseArr[config.url] = cancel
  }
  return config
}, error => {
  return Promise.reject(error)
})
// 响应拦截器即异常处理
axios.interceptors.response.use(response => {
  return response
}, (err) => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '错误请求'
        break
      case 401:
        err.message = '未授权，请重新登录'
        break
      case 403:
        err.message = '拒绝访问'
        break
      case 404:
        err.message = '请求错误,未找到该资源'
        break
      case 405:
        err.message = '请求方法未允许'
        break
      case 408:
        err.message = '请求超时'
        break
      case 429:
        err.message = '请求过多'
        break
      case 500:
        err.message = '服务器端出错'
        break
      case 501:
        err.message = '网络未实现'
        break
      case 502:
        err.message = '网络错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网络超时'
        break
      case 505:
        err.message = 'http版本不支持该请求'
        break
      default:
        err.message = `连接错误${err.response.status}`
    }
  } else {
    err.message = '连接服务器失败'
  }
  return Promise.reject(err.message)
})

export default {
  ...url,
  serverUrl,
  shareUrl,
  get (target, param) {
    axios.defaults.baseURL = target.type ? mockUrl : serverUrl
    const url = target.url
    return new Promise((resolve, reject) => {
      console.time(url)
      axios({
        method: 'get',
        url: url,
        params: param,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }]
      }).then(res => {
        resolve(res.data)
        console.timeEnd(url)
      }).catch(error => {
        Notification(
          {
            title: `${error}`,
            type: 'error',
            message: `GET:${url}`
          }
        )
        console.log('Get_Catch')
        reject(error)
      })
    })
  },
  post (target, param) {
    axios.defaults.baseURL = target.type ? mockUrl : serverUrl
    const url = target.url
    return new Promise((resolve, reject) => {
      console.time(url)
      axios({
        method: 'post',
        url: url,
        data: param,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }]
      }).then(res => {
        resolve(res.data)
        console.timeEnd(url)
      }, err => {
        Notification(
          {
            title: `${err}`,
            type: 'error',
            message: `POST:${url}`
          }
        )
      }).catch(error => {
        console.log('Post_Catch')
        reject(error)
      })
    })
  },
  downloadFile (target, param) {
    axios.defaults.baseURL = target.type ? mockUrl : serverUrl
    const url = target.url
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: url,
        data: param,
        responseType: 'blob',
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }]
      }).then(res => {
        this.download(res.data, param.name)
      }, err => {
        Notification(
          {
            title: `${err}`,
            type: 'error',
            message: `download:${url}`
          }
        )
      }).catch(error => {
        console.log('Post_Catch')
        reject(error)
      })
    })
  },
  download (data, name) {
    if (!data) {
      return
    }
    let url = window.URL.createObjectURL(new Blob([data]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', name)
    document.body.appendChild(link)
    link.click()
  }
}
